<?php

namespace App\Http\Validate\Article;

use AlibabaCloud\SDK\Dyvmsapi\V20170525\Models\ListHotlineTransferNumberResponseBody\data\values;
use App\Error\BaseError;
use App\Exceptions\KfHttpResponseException;
use App\Http\Validate\AbstractBaseValidate;
use App\Models\Article\ArticleCategoryMappingsModel;
use App\Models\Article\ArticleCategoryModel;
use App\Models\Article\ArticleModel;
use App\Models\Article\ArticleRecommendModel;
use App\Models\BaseModel;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ArticleCategoryValidate extends AbstractBaseValidate
{
    function getRules(): array
    {
        // TODO: Implement getRules() method.
        return [];
    }

    function getAttributes(): array
    {
        // TODO: Implement getAttributes() method.
        return [];
    }

    function registerValidateRules(): void
    {
        // TODO: Implement registerValidateRules() method.
    }

    function getMessages(): array
    {
        // TODO: Implement getMessages() method.
        return [
            "id.unique" => "专题已绑定文章"
        ];
    }

    /**
     * 专题列表校验
     *
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function listValidate()
    {
        $params = request()->all();
        return self::getInstance()->validate(
            [
                "name",
                "description",
                "uid",
                "sortField",
                "sortOrder",
                "pageSize",
                "pageNum",
                "createStartTime",
                "createEndTime"
            ],
            $params,
            [
                "name"            => "sometimes|string|min:1",
                "description"     => "sometimes|string|min:1",
                "uid"             => "sometimes|int|min:1",
                "sortField"       => "sometimes|in:createdAt,articleCount,showNum,readNum,forwardNum,collectNum,supportNum",
                "sortOrder"       => "sometimes|in:descend,ascend",
                "pageSize"        => "required|int|min:1|max:100",
                "pageNum"         => "required|int|min:1",
                "createStartTime" => "sometimes|date_format:Y-m-d",
                "createEndTime"   => "sometimes|date_format:Y-m-d",
            ]
        );
    }

    /**
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function addValidate()
    {
        return self::getInstance()->validate(
            ["name", "description", "cover", "type", "sort"],
            request()->all(),
            [
                "name"        => self::stringValidateBuild(true, 50, 1),
                "description" => self::stringValidateBuild(true, 150, 1),
                "cover"       => "required|url",
                "sort"        => "required|int|min:1"
            ]
        );
    }

    /**
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function updateValidate(array $params)
    {
        return self::getInstance()->validate(
            ['id', "name", "description", "cover", "sort"],
            $params,
            [
                'id'          => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                        ->where("isDeleted", BaseModel::DELETE_NO)
                ],
                "name"        => self::stringValidateBuild(true, 50, 1),
                "description" => self::stringValidateBuild(true, 150, 1),
                "cover"       => "required|url",
                "sort"        => "required|int|min:1"
            ]
        );
    }


    /**
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function sortValidate(array $params)
    {
        return self::getInstance()->validate(
            ['id', "sort"],
            $params,
            [
                'id'   => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                        ->where("isDeleted", BaseModel::DELETE_NO)
                ],
                "sort" => "required|int|min:0"
            ]
        );
    }

    /**
     * 删除校验
     *
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function delValidate(array $params)
    {
        return self::getInstance()->validate(
            ["id"],
            $params,
            [
                "id" => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                        ->where("isDeleted", BaseModel::DELETE_NO),
//                    Rule::unique((new ArticleCategoryMappingsModel())->getTable(), "categoryId")
//                        ->where("isDeleted", BaseModel::DELETE_NO),
                    function ($attribute, $value, $fail) {
                        $exists = ArticleCategoryMappingsModel::query()
                                                              ->where("categoryId", $value)
                                                              ->where("isDeleted", 0)
                                                              ->with("articleRel")
                                                              ->whereHas("articleRel", function ($query) {
                                                                  $query->where("isDeleted", 0);
                                                              })
                                                              ->first();
                        if ($exists) {
                            $fail(vsprintf("专题已绑定文章 [%s]", [
                                $exists->articleRel->title
                            ]));
                        }
                    },
                    function ($attribute, $value, $fail) {
                        $exists = ArticleRecommendModel::query()->where("contentType",
                            ArticleRecommendModel::CONTENT_TYPE_CATEGORY)->where("articleId", $value)->first();
                        if ($exists) {
                            $fail(vsprintf("专题已绑定推荐位 [%s] [%s]", [
                                ArticleRecommendModel::TYPE_TEXT[$exists->type] ?? "-",
                                $exists->title
                            ]));
                        }
                    },
                ]
            ]
        );
    }

    /**
     * 详情校验
     *
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function detailValidate(array $params)
    {
        return self::getInstance()->validate(
            ["id"],
            $params,
            [
                "id" => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                        ->where("isDeleted", BaseModel::DELETE_NO)
                ]
            ]
        );
    }

    /**
     * 专题分类文章列表校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function articleListValidate(array $params)
    {
        return self::getInstance()->validate(
            [
                "id",
//                "title",
//                "pageSize",
//                "pageNum",
//                "sortType"
            ],
            $params,
            [
                "id" => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")->where("isDeleted", 0)
                ],
//                "title"    => "sometimes|string|min:1",
//                "sortType" => self::intInValidateBuild(true, ArticleCategoryMappingsModel::SORT_TYPE_TEXT),
//                "pageSize" => "required|int|min:1|max:100",
//                "pageNum"  => "required|int|min:1"
            ]
        );
    }

    /**
     * 专题分类文章排序校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function articleSortValidate(array $params)
    {
        return self::getInstance()->validate(
            [
                "articleId",
                "id",
                "sort"
            ],
            $params,
            [
                "id"          => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")->where("isDeleted", 0)
                ],
                "sort"        => "required|array|min:1",
                "sort.*.id"   => [
                    "int",
                    Rule::exists(
                        (new ArticleCategoryMappingsModel())->getTable(),
                        "articleId"
                    )->where("categoryId", $params["id"] ?? 0)->where("isDeleted", 0)
                ],
                "sort.*.sort" => [
                    "required",
                    "int",
                    "min:1"
                ]
            ]
        );
    }

    /**
     * 专题分类文章列表校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function articleAddValidate(array $params)
    {
        return self::getInstance()->validate(
            [
                "id",
                "articleIds"
            ],
            $params,
            [
                "id"           => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                ],
                "articleIds"   => "array|min:1",
                "articleIds.*" => [
                    "int",
                    Rule::exists((new ArticleModel())->getTable(), "id"),
                    Rule::unique(
                        (new ArticleCategoryMappingsModel())->getTable(),
                        "articleId"
                    )
//                        ->where("categoryId", $params["id"] ?? 0)
                        ->where("isDeleted", BaseModel::DELETE_NO)
                ]
            ],
            true,
            function ($params) {
                $params["articleIds"] = array_unique($params["articleIds"]);
                return $params;
            }
        );
    }

    /**
     * 专题分类文章列表校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function articleDelValidate(array $params)
    {
        return self::getInstance()->validate(
            [
                "id",
                "articleIds"
            ],
            $params,
            [
                "id"           => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                ],
                "articleIds"   => "array|min:1",
                "articleIds.*" => [
                    "int",
                    Rule::exists((new ArticleModel())->getTable(), "id"),
                    Rule::exists(
                        (new ArticleCategoryMappingsModel())->getTable(),
                        "articleId"
                    )->where("categoryId", $params["id"] ?? 0)->where("isDeleted", 0)
                ]
            ],
            true,
            function ($params) {
                $params["articleIds"] = array_unique($params["articleIds"]);
                return $params;
            }
        );
    }

    /**
     * 专题统计校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function groupStatisticsValidate(array $params)
    {
        return self::getInstance()->validate(
            [
                "startTime",
                "endTime",
                "categoryId",
                "export"
            ],
            $params,
            [
                "startTime"  => "required|date_format:Y-m-d",
                "endTime"    => "required|date_format:Y-m-d",
                "categoryId" => [
                    "sometimes",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                ],
                "export"     => "sometimes|in:0,1"
            ]
        );
    }

    /**
     * 专题统计校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function hotListValidate(array $params)
    {
        return self::getInstance()->validate(
            [
                "startTime",
                "endTime"
            ],
            $params,
            [
                "startTime" => "required|date_format:Y-m-d",
                "endTime"   => "required|date_format:Y-m-d"
            ]
        );
    }

    /**
     * 置顶校验
     *
     * @param $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function putTopValidate($params)
    {
        return self::getInstance()->validate(
            ["id", "putTop"],
            $params,
            [
                "id"     => [
                    "required",
                    "int",
                    Rule::exists((new ArticleCategoryModel())->getTable(), "id")
                ],
                "putTop" => self::intInValidateBuild(true, ArticleCategoryModel::PUT_TOP_TEXT)
            ]
        );
    }
}
